package com.xuanyuanxinyu.func.network.retrofit

import android.text.TextUtils
import android.util.Log
import com.xuanyuanxinyu.utils.log.AppLog
import com.xuanyuanxinyu.utils.log.AppLog.d
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

/**
 * 日志拦截
 */
class CustomInterceptor : Interceptor {
    val POST = "POST"
    val GET = "GET"
    
    @Throws(IOException::class)
    override fun intercept(chain : Interceptor.Chain) : Response {
        val request : Request = chain.request()
        val startTime = System.currentTimeMillis()
        val endTime = System.currentTimeMillis()
        val duration = endTime - startTime
        // 请求类型 POST或GET
        val methodType = request.method.uppercase()
        
        
        d(RetrofitManager::class.java, AppLog.GROUP_RETROFIT, RetrofitManager.TAG + "----------Start----------------\n")
        
        if (POST == methodType) {
            val sb = StringBuilder()
            if (request.body is FormBody) {
                val body = request.body as FormBody
                for (i in 0 until body.size) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",")
                }
                sb.delete(sb.length - 1,sb.length)
                d(
                    RetrofitManager::class.java,
                    AppLog.GROUP_RETROFIT,
                    RetrofitManager.TAG + "|" + " RequestParams:{$sb})")
            }
        }
        //        val body = response.body //获取响应体
        //        // 由于ResponseBody内的bytes()、string()方法调用了closeQuietly方法，此方法会将ResponseBody内的数据源清除，所以仅获取一次内容。
        //        val bytes = body!!.bytes() //获取字节数组
        // ************* Response *************
        var response : Response = chain.proceed(chain.request())
        // 响应Code
        val responseCode = response.code
        // "application/octet-stream" 是header类型
        val headerContentType = response.header("content-type")
        
        response.body?.apply {
            val source = source()
            // 返回数据类型
            val responseContentType = contentType()
            // 请求response响应内容
            val content = string()
            Log.d(RetrofitManager.TAG,"| Response:$content")
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer
            val body = buffer.clone().readString(Charset.forName("UTF-8"))
            if (!TextUtils.isEmpty(body) && body.contains("\"error_code\":\"RM.100109\"")) {
                // TODO 拦截指定返回的错误码信息
                // TODO 发送消息，收到特定的错误码，进行统一的拦截处理
            }
            val responseData = bytes()
            // 创建新的Response
            response = response.newBuilder() .headers(response.headers).body(responseData.toResponseBody(responseContentType)).build()
        }
        
        d(RetrofitManager::class.java,AppLog.GROUP_RETROFIT, RetrofitManager.TAG + "------------End:" + duration + "毫秒----------")
        return response
    }
}

/**
 * 将400·403状态码转换为200，默认的OKHttp 200Code对应的只有400
 *
 */
class CustomInterceptor2 : Interceptor {
    override fun intercept(chain : Interceptor.Chain) : Response {
        val request = chain.request()
        var response = chain.proceed(request)
        if (response.code in 400..403) {
            val currentResponseBody = response.body
            if (null != currentResponseBody) {
                val responseData = currentResponseBody.bytes()
                val mediaType = currentResponseBody.contentType()
                response = response.newBuilder().body(ResponseBody.create(mediaType,responseData))
                    .code(200).build()
            }
        }
        return response
    }
}

/**
 * 指定URL的拦截器
 * 对于指定的URL的网络请求进行网络配置修改
 * 例如下：对指定URL进行配置时间的修改
 */
class AppointUrlInterceptor : Interceptor {
    override fun intercept(chain : Interceptor.Chain) : Response {
        val request = chain.request()
        val response : Response
        val requestUrl = request.url.toString()
        if (requestUrl.contains("/sdk/info",false)) {
            response = chain.withConnectTimeout(1300,TimeUnit.MILLISECONDS)
                .withReadTimeout(1300,TimeUnit.MILLISECONDS)
                .withWriteTimeout(1300,TimeUnit.MILLISECONDS).proceed(request)
            return response
        } else {
            response = chain.proceed(request)
        }
        return response
    }
}
///**
// * 网络请求日志打印
// */
//class CustomerHttpLogger : HttpLoggingInterceptor.Logger {
//    override fun log(message : String) {
//        //okHttp的详细日志会打印出来
//        val text = URLDecoder.decode(message, "utf-8")
//
//    }
//}
/**
 * 网络请求日志自定义打印
 */
fun getCustomerLogInterceptor() : HttpLoggingInterceptor {
    val interceptor = HttpLoggingInterceptor { message->
        try {
            var value = message.replace("%(?![0-9a-fA-F]{2})".toRegex(),"%25")
            value = value.replace("\\+".toRegex(),"%2B")
            val text = URLDecoder.decode(value,"utf-8")
            d(HttpLoggingInterceptor::class.java,
                AppLog.GROUP_VIEW,
                "getCustomerLogInterceptor()  网络请求日志 message=$message")
        } catch (e : UnsupportedEncodingException) {
            d(HttpLoggingInterceptor::class.java,
                AppLog.GROUP_VIEW,
                "getCustomerLogInterceptor()  网络请求日志 异常 e=${e.message}")
        }
    }
    // 这一句一定要记得写，否则没有数据输出
    val level = interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
    return interceptor
}

